/**
 * Created by leiqr on 2015/6/9.
 */
define(function (require, exports, module) {
    var $ = require("jquery");
    var template = require("template");
    require('jquerycookie');
    require('./topNotice');
    require('jqueryAppear');
    require('jquerySuperslide');
    require('jqueryPagination');
    require('./toTop');
    //require('jqueryBizQQ');
    var dialogModule = require('js/goToLogin');

    // var api_prefix = "/api/index.php?r=cms/cms-search/"; //api前缀
    var api_prefix = api_domain + "/api/index.php?r=cms/cms-search/"; //api前缀
    var jsopName = "jsonp_data";
    var main = {
        pageCount: 10,//分页每页显示20条
        curpage: 0,
        init: function () {
            template.helper('encodeURL', function (str) {
                return encodeURIComponent(str);
            });
            var self = this, defer,
                keyword = this.getQueryParams('keyword');
            if (keyword) {
                $("#keyword").val(keyword);
            }
            defer = this.requestData(),
                defer.then(function (res) {
                    if(!res){
                        dialogModule.dialog.showModal();
                        return;
                    }
                    self.bindEvt();
                    self.fillData(res);               
                    self.createPaging(res.count);
                    self.animationOnScroll();
                    self.fullSlide();
                })
            //$.BizQQ([{selector: 'js_BizQQWPA'},{selector: 'BizQQWPC'}]);
        },
        createPaging: function (len) {
            var self = this;
            $("#pagination").pagination(len, {
                num_edge_entries: 1, //边缘页数
                num_display_entries: 4, //主体页数
                callback: function (index) {
                    self.curpage = index - 1;
                    self.requestData()
                        .then(function(res){
                            
                            self.fillData(res); 
                        })
                },
                items_per_page: self.pageCount, //每页显示1项
                prev_text: "前一页",
                next_text: "后一页"
            });

        },
        bindEvt: function () {
            var self = this;
            // $("#searchBtn").click(function () {
            //     //self.requestData().then(function(res){
            //     //    self.fillData(res);
            //     //});
            //     self.keyword = $("#keyword").val();
            //     location.search = "?keyword=" + encodeURIComponent(self.keyword);
            // });
//             $("#keyword").on('keypress', function (evt) {
//                 if (evt.which == 13) {
//                     //    self.requestData().then( function(res){
//                     //            self.fillData(res);
//                     //        }
//                     //    )
//                     self.keyword = $("#keyword").val();
//                     location.search = "?keyword=" + encodeURIComponent(self.keyword);
//                 }
// 
//             });
            $('#navbar').click(function(e){
                var target = $(e.target);
                
                var aid = target.data('aid') || target.parent().data('aid');
                
                if (aid !== undefined) {
                    var pid = target.data('pid') || target.parent().data('pid');
                    location.href = "list.html?dirId=" + aid + "&pid=" + pid;
                }
            });
        },
        requestData: function () {
            var self = this;
            this.keyword = $("#keyword").val();
            var url = api_prefix + "search&keyword=" + encodeURIComponent(this.keyword) + "&limit=" + this.pageCount + "&offset=" + this.curpage + '&jsonp=' + jsopName;
            var defer = $.Deferred();
            $.getScript(url, function () {
                defer.resolve(window[jsopName]);
            });
            return defer.promise();
        },
        getQueryParams: function (para) {
            var reg = new RegExp("(^|&)" + para + "=([^&]*)(&|$)");
            var r = window.location.search.substr(1).match(reg);
            if (r != null) {
                return decodeURIComponent(r[2]);
            }
            return null;
        },
        /**
         * 填充数据
         * @param   res Obj
         */
        fillData: function (res) {
            var total = res.count;
            res = res.data;
            if (res && res.length > 0) {
                var data = {}, html = '';
                //配置template格式化日期
                template.helper('dateFormat', function (date, format) {
                    var reg = /\d+/g;
                    if (reg.test(date)) {
                        date = (date - 0) * 1000;
                    }
                    date = new Date(date);

                    var map = {
                        "M": date.getMonth() + 1, //月份
                        "d": date.getDate(), //日
                        "h": date.getHours(), //小时
                        "m": date.getMinutes(), //分
                        "s": date.getSeconds(), //秒
                        "q": Math.floor((date.getMonth() + 3) / 3), //季度
                        "S": date.getMilliseconds() //毫秒
                    };
                    format = format.replace(/([yMdhmsqS])+/g, function (all, t) {
                        var v = map[t];
                        if (v !== undefined) {
                            if (all.length > 1) {
                                v = '0' + v;
                                v = v.substr(v.length - 2);
                            }
                            return v;
                        }
                        else if (t === 'y') {
                            return (date.getFullYear() + '').substr(4 - all.length);
                        }
                        return all;
                    });
                    return format;
                });
                data.keyword = this.keyword;
                var keywordReg = new RegExp(this.keyword, 'gi');
                for (var i = 0; i < res.length; i++) {
                    res[i].content = res[i].content.replace(/&lt;/g, '<').replace(/&gt;/g, '>');
                    res[i].content = res[i].content.replace(/<[^>]+>/g, "").replace(/&amp;nbsp;/g,'');
                    res[i].title = res[i].title.replace(/&lt;/g, '<').replace(/&gt;/g, '>');
                    res[i].title = res[i].title.replace(/<[^>]+>/g, "").replace(/&amp;nbsp;/g,'');
                    if (res[i].content.length > 140) {
                        res[i].content = res[i].content.substring(0, 140) + '...';
                    }
                    if (res[i].title.length > 14) {
                        res[i].title = res[i].title.substring(0, 14) + '...';
                    }
                    res[i].content = res[i].content.replace(keywordReg, "<span style='color:red;'>" + this.keyword + "</span>");
                    res[i].title = res[i].title.replace(keywordReg, "<span style='color:red;'>" + this.keyword + "</span>");
                }
                data.list = res;
                data.total = total;
                template.config('escape', false);//是否编码输出 HTML 字符
                html = template('result', data);
                $("#resultDiv").html(html);
                $('#search').show();
            } else {
                $('#search').hide();
                $('#noresult').show().find('#key').html(this.getQueryParams('keyword'));
            }
        },
        animationOnScroll: function () {
            $('.animated').appear(function () {
                var elem = $(this);
                var animation = elem.data('animation');
                if (!elem.hasClass('visible')) {
                    var animationDelay = elem.data('animation-delay');
                    if (animationDelay) {
                        setTimeout(function () {
                            elem.addClass(animation + " visible");
                        }, animationDelay);
                    } else {
                        elem.addClass(animation + " visible");
                    }
                }
            });
        },
        fullSlide: function () {
            $(".fullSlide").hover(function () {
                $(this).find(".prev,.next").stop(true, true).fadeIn()
            }, function () {
                $(this).find(".prev,.next").fadeOut()
            });
            $(".fullSlide").slide({
                titCell: ".hd",
                mainCell: ".bd",
                effect: "fold",
                autoPlay: true,
                autoPage: true,
                trigger: "click",
                startFun: function (i) {
                    var curLi = $(".fullSlide .bd li").eq(i);
                    if (!!curLi.attr("_src")) {
                        curLi.css("background-image", curLi.attr("_src")).removeAttr("_src")
                    }
                }
            });
        }
    };
    main.init();
});
